package com.jp.kefu.util;

import com.jp.kefu.web.message.AbstractMessage;
import com.jp.kefu.web.message.MergedMessage;
import com.jp.kefu.web.message.common.LinkMessage;
import com.jp.kefu.web.message.common.LocationMessage;
import com.jp.kefu.web.message.common.TextMessage;
import com.jp.kefu.web.message.event.*;
import com.jp.kefu.web.message.media.ImageMessage;
import com.jp.kefu.web.message.media.VideoMessage;
import com.jp.kefu.web.message.media.VoiceMessage;
import com.thoughtworks.xstream.XStream;
import org.apache.ibatis.parsing.XPathParser;
import org.springframework.beans.BeanUtils;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

/**
 * Created by Administrator on 2017/7/25.
 */
public abstract  class XMLUtils {
    private static final XStream xStream = new XStream();

    public static AbstractMessage parse(String xml) {


        xStream.alias("xml", MergedMessage.class);
        MergedMessage mergedMessage = (MergedMessage)xStream.fromXML(xml);;


        AbstractMessage.MsgType msgType = mergedMessage.getMsgType();
        AbstractMessage msg = mergedMessage;
        switch (msgType) {
            //普通消息
            case text:
                msg = new TextMessage();
                break;
            case image:
                msg = new ImageMessage();
                break;
            case voice:
                msg = new VoiceMessage();
                break;
            case video:
            case shortvideo:
                msg = new VideoMessage();
                break;
            case location:
                msg= new LocationMessage();
                break;
            case link:
                msg = new LinkMessage();
                break;
                //事件
            case event:
                Event.EventType eventType = mergedMessage.getEvent();
                switch (eventType) {
                    case subscribe:
                    case unsubscribe:
                        msg = new SubscribeEvent();
                        break;
                    case SCAN:
                        msg = new ScanQrcodeEvent();
                        break;
                    case LOCATION:
                        msg = new ReportLocationEvent();
                        break;
                    case CLICK:
                    case VIEW:
                        msg = new MenuClickEvent();
                        break;
                }
                break;
        }
        BeanUtils.copyProperties(mergedMessage, msg);
        return msg;
    }

    public static String print(AbstractMessage msg) {
        xStream.alias("xml", msg.getClass());
        return xStream.toXML(msg);
    }
}
